package com.example.fw;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;

import com.example.tests.ContactObject;

public class ContactHelper extends HelperWithWebDriverBase {

	public ContactHelper(ApplicationManager manager) {
		super(manager);
	}

	public Set<ContactObject> getContacts() {
		manager.getNavigationHelper().openMainPage();
		WebElement table = findElements(By.tagName("table")).get(0);
		List<WebElement> checkboxes = table.findElements(By.name("selected[]"));
		Set<ContactObject> contacts = new HashSet<ContactObject>();
		for (WebElement checkbox : checkboxes) {
			String title = checkbox.getAttribute("title");
			//
			title = title.substring("Select (".length(),
					title.length() - ")".length());
			//
			ContactObject contact = new ContactObject().setFirstName(title).setId(
					checkbox.getAttribute("value"));
			contacts.add(contact);
		}
		return contacts;
	}

	public void createContact(ContactObject contactObject) {
		manager.getNavigationHelper().openMainPage();
		startContactCreation();
		fillContactForm(contactObject);
		submitContactCreation();
		returnToMainPage();
	}

	public void deleteContact(int i) {
		manager.getNavigationHelper().openMainPage();
		initContactModification(i);
		click(By.xpath("(//input[@name='update'])[2]"));
		returnToMainPage();
	}

	public void modifyContact(int i, ContactObject validContact) {
		manager.getNavigationHelper().openMainPage();
		initContactModification(i);
		fillContactForm(validContact);
		click(By.xpath("(//input[@name='update'])[1]"));
		returnToMainPage();
	}

	protected void startContactCreation() {
		click(By.linkText("add new"));
	}

	protected void returnToMainPage() {
		click(By.linkText("home page"));
	}

	protected void submitContactCreation() {
		click(By.name("submit"));
	}

	protected void initContactModification(int i) {
		click(By.xpath("(//img[@alt='Edit'])[" + i + "]"));

	}

	protected void fillContactForm(ContactObject contactObject) {
		type(By.name("firstname"), contactObject.firstName);
		type(By.name("lastname"), contactObject.lastName);
		type(By.name("address"), contactObject.addressFirst);
		type(By.name("home"), contactObject.homePhone);
		type(By.name("mobile"), contactObject.mobilePhone);
		type(By.name("work"), contactObject.workPhone);
		type(By.name("email"), contactObject.emailFirst);
		type(By.name("email2"), contactObject.emailSecond);
		selectElementFromDropDownList(By.name("bday"), contactObject.birthDate);
		selectElementFromDropDownList(By.name("bmonth"), contactObject.birthMonth);
		type(By.name("byear"), contactObject.birthYear);
		type(By.name("address2"), contactObject.addressSecond);
		type(By.name("phone2"), contactObject.phoneSecond);
	}

}
